﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HalconDotNet;
using ViewWindow;

namespace ViewROI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        List<ViewWindow.Model.ROI> regions;//roi集合
        HObject ho_ModelImage;
        private bool draw = false;//是否要绘制
        private int style = 0;//要绘制的类型0--直线，1圆，2，矩形，3，角度矩形，4，扇形

        private Rectangle depart;//为了记录图像的原始状态（20191030)
        double row1, col1, row2, col2;

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {

            this.regions = new List<ViewWindow.Model.ROI>();

            ho_ModelImage = new HObject();
            HOperatorSet.ReadImage(out this.ho_ModelImage, "测试.bmp");

            //显示背景图
            hWindow_Fit1.HobjectToHimage(ho_ModelImage);

            //注册窗口鼠标事件
            hWindow_Fit1.hWindowControl.MouseUp += Hwindow_MouseUp;
            hWindow_Fit1.hWindowControl.MouseDown += HWindowControl_MouseDown;
        }

        private void HWindowControl_MouseDown(object sender, MouseEventArgs e)
        {
            int index;

            List<HTuple> data;
            ViewWindow.Model.ROI roi = hWindow_Fit1.viewWindow.smallestActiveROI(out data, out index);//可以获取最后一次选中或者编辑对象的数据

            if (index > -1)
            {
               string name = roi.GetType().Name;//得到最后一次选中的对象名字
               this.dgv_ROI.Rows[index].Cells[0].Selected = true;
               this.regions[index] = roi;//这里更新了数据---这句话非常重要
            }

            if (draw == false) return;
            hWindow_Fit1.hWindowControl.HalconWindow.GetMposition(out int y, out int x, out int b);
           
          //  this.Text = b.ToString();
            if (b == 4)
            {
                draw = false;
                return;//按下的是右键
            }
            switch(style)
            {
                case 0://dian
                    hWindow_Fit1.viewWindow.genPoint(y, x , ref this.regions);
                    break;

                case 1://直线
                    hWindow_Fit1.viewWindow.genLine(y, x - 20, y, x + 20, ref this.regions);
                    break;
                   
                case 2://圆
                    hWindow_Fit1.viewWindow.genCircle(y, x, 60.0, ref this.regions);
                    break;
                case 3://矩形
                  // hWindow_Fit1.viewWindow.genLine(y, x - 20, y, x + 20, ref this.region1s);
                     hWindow_Fit1.viewWindow.genRect1(y-50, x-50, y+50, x+50, ref this.regions);
                    break;
                case 4://角度矩形
                    hWindow_Fit1.viewWindow.genRect2(y, x, 30.0 / 180.0 * Math.PI, 60.0, 30.0, ref this.regions);
                    break;
                case 5://扇形
                    hWindow_Fit1.viewWindow.genCircularArc(y, x, 40.0, 0, -3.14, "negative", ref this.regions);
                    break;
                default: draw = false;//退出
                    return;
                   

            }
           
            this.regions.Last().Color = "blue";
            binDataGridView(this.dgv_ROI, this.regions);
            draw = false;
        }

        void binDataGridView(DataGridView dgv, List<ViewWindow.Model.ROI> config)
        {
            try
            {

                dgv.DataSource = null;

                DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
                column1.DataPropertyName = "Type";
                column1.HeaderText = "类型";
                column1.Name = "Type";
                column1.Width = 90;
                column1.ReadOnly = true;

                dgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { column1 });
                dgv.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dgv.AllowUserToDeleteRows = true;
                dgv.AllowUserToAddRows = false;
                dgv.MultiSelect = false;
                dgv.AllowUserToAddRows = false;//禁止添加行
                dgv.AllowUserToDeleteRows = true;//禁止删除行
                //dgv.ContextMenuStrip = contextMenuStrip;
                dgv.DataSource = config;
                dgv.Refresh();
                if (config.Count > 0)
                {
                   dgv.Rows[config.Count - 1].Cells[0].Selected = true;
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 加载图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_LoadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog opnDlg = new OpenFileDialog();
            opnDlg.Filter = "所有图像文件 | *.bmp; *.pcx; *.png; *.jpg; *.gif;" +
                "*.tiff; *.ico; *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf";
            opnDlg.Title = "打开图像文件";
            opnDlg.ShowHelp = true;
            opnDlg.Multiselect = false;
            //opnDlg.InitialDirectory = startImagePath;

            if (opnDlg.ShowDialog() == DialogResult.OK)
            {
                string filename = opnDlg.FileName;

                HOperatorSet.GenEmptyObj(out this.ho_ModelImage);
                this.ho_ModelImage.Dispose();
                HOperatorSet.ReadImage(out this.ho_ModelImage, filename);

                hWindow_Fit1.HobjectToHimage(ho_ModelImage);
                //this._windowControl.displayImage(this.ho_ModelImage);
                hWindow_Fit1.viewWindow.displayROI(this.regions);


                HObject reG = new HObject();
                HOperatorSet.GenCrossContourXld(out reG, 500, 500, 1000, 1);
                
                HObject im = new HObject();
               // HOperatorSet.ReadImage(out im, "C:\\Users\\ThinkPad\\Desktop\\temp\\1.png");
                

                HObject rec = new HObject();
                HOperatorSet.GenRectangle1(out rec, 1100, 0, 1600, 200);

                hWindow_Fit1.DispObj(im);
                hWindow_Fit1.DispObj(reG);
                hWindow_Fit1.DispObj(rec);

                reG.Dispose();
                rec.Dispose();

                
            }


        }

#region 绘制roi
       
        private void Rect1Button_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.viewWindow.genRect1(110.0, 110.0, 210.0, 210.0, ref this.regions);
            this.regions.Last().Color = "blue";
            binDataGridView(this.dgv_ROI, this.regions);
        }

        private void Rect2Button_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.viewWindow.genRect2(200.0, 200.0, 30.0/180.0*Math.PI, 60.0, 30.0, ref this.regions);
            //设置roi的颜色
            this.regions.Last().Color = "blue";
            binDataGridView(this.dgv_ROI, this.regions);
        }

        private void CircleButton_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.viewWindow.genCircle(200.0, 200.0, 60.0, ref this.regions);
            this.regions.Last().Color = "blue";
            binDataGridView(this.dgv_ROI, this.regions);
        }

        private void LineButton_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.viewWindow.genLine(100.0, 100.0, 100.0, 100.0, ref this.regions);
            this.regions.Last().Color = "blue";
            binDataGridView(this.dgv_ROI, this.regions);
        }

        private void DelActROIButton_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.viewWindow.removeActiveROI(ref this.regions);
            binDataGridView(this.dgv_ROI, this.regions);
        }

#endregion

        /// <summary>
        /// 将roi和DataGridView关联显示
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="config"></param>
        private void dgv_ROI_CellClick(object sender, DataGridViewCellEventArgs e)
        {
           

        }


        /// <summary>
        /// 注册haclon窗体的鼠标弹起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Hwindow_MouseUp(object sender, MouseEventArgs e)//没有在里面写代码，写到down事件下了
        {

        }


        /// <summary>
        /// 禁止缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {

            hWindow_Fit1.DrawModel = true;
        }

        /// <summary>
        /// 允许缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.DrawModel = false;
        }

        /// <summary>
        /// 显示region
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            HObject region1 = new HObject();
            HOperatorSet.GenRectangle1(out region1,20,20,600,600);
            //默认显示红色的region
            hWindow_Fit1.DispObj(region1);
            region1.Dispose();

            HObject region2 = new HObject();
            HOperatorSet.GenRectangle1(out region2, 600, 600, 900, 900);
            //显示成黄色
            hWindow_Fit1.DispObj(region2,"yellow");
            region2.Dispose();
        }

        /// <summary>
        /// 显示xld
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            HObject cross1 = new HObject();
            HOperatorSet.GenCrossContourXld(out cross1,200,200,300,0);
            //默认显示红色的xld
            hWindow_Fit1.DispObj(cross1);
            cross1.Dispose();


            HObject cross2 = new HObject();
            HOperatorSet.GenCrossContourXld(out cross2, 900, 900, 300, 4);
            //显示成蓝色
            hWindow_Fit1.DispObj(cross2,"blue");
            cross2.Dispose();
        }

        /// <summary>
        /// 显示截图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {

            HObject region1 = new HObject();
            HObject reduce_image = new HObject();

            HOperatorSet.GenRectangle1(out region1, 30, 30, 700, 700);
            HOperatorSet.ReduceDomain(ho_ModelImage, region1, out reduce_image);

            hWindow_Fit1.DispObj(reduce_image);
            region1.Dispose();
            reduce_image.Dispose();

        }

        private void button7_Click(object sender, EventArgs e)

        {
            if (0 == regions.Count) return;
            string str = regions[0].Type;
            
           HTuple x= regions[0].getModelData();
            // hWindow_Fit1.viewWindow.genRect1(110.0, 110.0, 210.0, 210.0, ref this.regions);
             regions[0].createRectangle1(200, 200, 400, 400);

          
            hWindow_Fit1.viewWindow.selectROI(0);
           // MessageBox.Show(str);
        }

        private void groupBox5_Enter(object sender, EventArgs e)
        {

        }

        private void button8_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.EditModel = true;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.EditModel = false;
        }

        private void button10_Click(object sender, EventArgs e)
        {
            //there 0.5>0 is "positive" else "negative"
            //hWindow_Fit1.viewWindow.genCircularArc(100.0, 100.0, 40.0, 0, 3.14, "positive", ref this.regions);
           hWindow_Fit1.viewWindow.genCircularArc(100.0, 100.0, 40.0, 0, -3.14, "negative", ref this.regions);

           

            this.regions.Last().Color = "blue";
            binDataGridView(this.dgv_ROI, this.regions);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            draw = true;
            style = 2;
          //  hWindow_Fit1.HobjectToHimage(ho_ModelImage);
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void dgv_ROI_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void hWindow_Fit1_MouseClick(object sender, MouseEventArgs e)
        {
            MessageBox.Show("1");
        }

        private void button12_Click(object sender, EventArgs e)
        {
            //显示背景图
            hWindow_Fit1.HobjectToHimage(ho_ModelImage);
            hWindow_Fit1.viewWindow.displayROI(this.regions);
            if (0 == regions.Count) return;
            hWindow_Fit1.viewWindow.selectROI(0);
        }

        private void button13_Click(object sender, EventArgs e)
        {
            draw = true;
            style = 1;
        }

        private void button14_Click(object sender, EventArgs e)
        {
            draw = true;
            style = 3;
        }

        private void button15_Click(object sender, EventArgs e)
        {
            draw = true;
            style = 4;
        }

        private void button16_Click(object sender, EventArgs e)
        {
            draw = true;
            style = 5;
        }

        private void dgv_ROI_CellEnter(object sender, DataGridViewCellEventArgs e)//点击立即发生
        {

            int index;
            string name = "";
            List<HTuple> data;

            hWindow_Fit1.viewWindow.selectROI(e.RowIndex);//这里只需要这一句就够了，
            ViewWindow.Model.ROI roi = hWindow_Fit1.viewWindow.smallestActiveROI(out data, out index);

            if (index > -1)
            {
                name = roi.GetType().Name;
            }
        }

        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                this.hWindow_Fit1.viewWindow.saveROI(this.regions, Application.StartupPath + "\\view.xlm");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
           
        }

        private void button18_Click(object sender, EventArgs e)
        {
            try
            {
                this.hWindow_Fit1.viewWindow.loadROI(Application.StartupPath + "\\view.xlm", out this.regions);
                //下面是显示代码
                hWindow_Fit1.HobjectToHimage(ho_ModelImage);
                hWindow_Fit1.viewWindow.displayROI(this.regions);
                binDataGridView(this.dgv_ROI, this.regions);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
         
        }

        private void button19_Click(object sender, EventArgs e)
        {
            if (this.regions.Count == 0) return;

            this.regions[0].Msize = new Size(4, 4);
           
            hWindow_Fit1.viewWindow._roiController.ROIList[0] = this.regions[0];//这里更新窗体显示

            binDataGridView(this.dgv_ROI, this.regions);//这里更新dataviewgrid

        }


        private void button25_Click(object sender, EventArgs e)
        {
            // depart = hWindow_Fit1.viewWindow.getPart();
            depart = hWindow_Fit1.hWindowControl.ImagePart;
            //startx = hWindow_Fit1.viewWindow._hWndControl.startX;
            //starty = hWindow_Fit1.viewWindow._hWndControl.startX;
            //d = hWindow_Fit1.viewWindow._hWndControl.zoomWndFactor;
            //d1 = hWindow_Fit1.viewWindow._hWndControl.zoomAddOn;
            //d2 = hWindow_Fit1.viewWindow._hWndControl.zoomWndSize;
            //hw = hWindow_Fit1.viewWindow._hWndControl.ZoomWindow;

            row1 = hWindow_Fit1.viewWindow._hWndControl.ImgRow1;
            row2 = hWindow_Fit1.viewWindow._hWndControl.ImgRow2;
            col1 = hWindow_Fit1.viewWindow._hWndControl.ImgCol1;
            col2 = hWindow_Fit1.viewWindow._hWndControl.ImgCol2;
            this.Text = col2.ToString();
        }

        private void 查看坐标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //首先确定当前选择项目
            if (dgv_ROI.CurrentCell is null)
            {
                //没有任何选中
                return;
            }
            int order = dgv_ROI.CurrentCell.RowIndex;//找到所处的行
            HTuple x = regions[order].getModelData();
            string strTemp = "序号: " + order.ToString() + " 类型：" + regions[order].Type + " 坐标:";
            for (int i = 0; i < x.Length; i++)
            {
                if (strTemp.Contains("Arc"))
                {
                    if (i != (x.Length - 1))
                    {
                        strTemp += x[i].D.ToString("F6") + ",";
                    }
                    else//结尾
                    {
                        strTemp += x[i].S;
                    }
                }
                else
                {
                    if (i != (x.Length - 1))
                    {
                        strTemp += x[i].D.ToString("F6") + ",";
                    }
                    else//结尾
                    {
                        strTemp += x[i].D.ToString("F6");
                    }
                }
            }
            MessageBox.Show(strTemp);
        }

        private void button20_Click(object sender, EventArgs e)
        {
            
            hWindow_Fit1.DispText("hello\r\n你好\r\n"+"asdasdas", "yellow", 300, 50,20,"mono","true","true");
            //hWindow_Fit1.DispText("hello\r\n你好\r\n1", "white", "top", "left", 20, "宋体", "false", "false");
            // hWindow_Fit1.DispText("hello0", "window", "white", "top", "left");
        }

        private void button21_Click(object sender, EventArgs e)
        {
            //HImage image = new HImage(@"C: \Users\zz132\Desktop\0910划伤\0910划伤\03_SingleScrach.png");
            //Image img = Image.FromFile(@"E:\MyAllExample\开源\ihalcon开源窗体控件\ihalcon开源窗体控件\控件demo\控件demo\bin\Debug\测试.bmp");
            //hWindow_Fit1.BackgroundImage = img;

        }

        private void button22_Click(object sender, EventArgs e)
        {
            hWindow_Fit1.viewWindow.genPoint(800.0, 800.0, ref this.regions);
            this.regions.Last().Color = "blue";
            binDataGridView(this.dgv_ROI, this.regions);
        }

        private void button23_Click(object sender, EventArgs e)
        {
            draw = true;
            style = 0;
        }

        private void button24_Click(object sender, EventArgs e)
        {

            hWindow_Fit1.hWindowControl.ImagePart = depart;

            hWindow_Fit1.viewWindow._hWndControl.ImgRow1 = row1;
            hWindow_Fit1.viewWindow._hWndControl.ImgRow2 = row2;
            hWindow_Fit1.viewWindow._hWndControl.ImgCol1 = col1;
            hWindow_Fit1.viewWindow._hWndControl.ImgCol2 = col2;

            hWindow_Fit1.viewWindow.repaint();//重绘


          
        }
    }
}
